package com.qzy.reggie.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qzy.reggie.common.PageResult;
import com.qzy.reggie.common.Result;
import com.qzy.reggie.pojo.Category;
import com.qzy.reggie.service.Two_CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/category")
public class Two_CategoryController {

    @Autowired
    private Two_CategoryService twoCategoryService;


    @GetMapping()
    public Result page(Integer page,Integer pageSize){
        // 使用Mybatis的PageHelper插件完成分页功能

        // 1.通过插件，设置分页信息
        PageHelper.startPage(page,pageSize);

        List<Category> categories = twoCategoryService.queryCategoryList(null);

        // 3.封装PageInfo对象，获取分页total
        PageInfo<Category> pageInfo = new PageInfo<>(categories);

        return Result.success("查询成功",new PageResult(pageInfo.getTotal(),categories));
    }

    @GetMapping("list")
    public Result list(Category category){
        List<Category> categories  = twoCategoryService.queryCategoryList(category);

        return Result.success("查询成功",categories);
    }

    @PostMapping()
    public Result save(@RequestBody Category category,HttpSession session){

        Long empId = (Long) session.getAttribute("empId");

        // 完善系统信息
        category.setCreateUser(empId);
        category.setUpdateUser(empId);
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());


        Integer ret = twoCategoryService.save(category);

        if (ret > 0){
            return Result.success("新增成功");
        }else{
            return Result.error("新增失败");
        }
    }

    // http://localhost:8080/Category/1
    @GetMapping("{id}")
    public Result getCategoryById(@PathVariable Long id){
        return Result.success(twoCategoryService.getCategoryById(id));
    }

    @PutMapping()
    public Result updateCategory(@RequestBody Category category,HttpSession session){
        Long empId = (Long) session.getAttribute("empId");
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(empId);

        Integer ret = twoCategoryService.update(category);

        if (ret > 0){
            return Result.success("修改成功");
        }else{
            return Result.error("修改失败");
        }
    }

    @DeleteMapping("{id}")
    public Result delete(@PathVariable Long id){
        Integer ret = twoCategoryService.deleteCategory(id);

        if (ret > 0){
            return Result.success("修改成功");
        }else{
            return Result.error("修改失败");
        }
    }
}
